<template>
  <span
    v-if="icon.type === 'svg' && icon.content"
    v-html="icon.content"
    class="cc-icon"
    :style="style"
  ></span>
  <img
    v-else-if="icon.type === 'base64' && icon.content"
    :src="'data:image/png;base64,' + icon.content"
    :height="size ? (size + 'px') : '30px'"
    alt=""
  />
</template>

<script setup>
import { onMounted, ref, watch, computed } from 'vue';
import { getIconList } from '@/utils/system';

const props = defineProps({
  iconId: {
    type: String,
    default: ''
  },
  icon: {
    type: Object,
    default: null
  },
  size: [Number, String],
  color: {
    type: String,
    default: ''
  },
});

const icon = ref({});

const init = async() => {
  if (props.icon) {
    icon.value = props.icon;
  } else if (props.iconId) {
    let iconList = await getIconList();
    icon.value = iconList.find(item => item.id === props.iconId) || {};
  }
};

const style = computed(() => {
  let style = '';
  if (props.size) {
    style += 'font-size: ' + props.size + 'px;';
  }
  if (props.color) {
    style += 'color: ' + props.color + ';';
  }
  return style;
});

watch(() => props, () => {
  init();
}, {deep: 1});

onMounted(() => {
  init();
});
</script>

<style scoped>
.cc-icon {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  font-size: inherit;
  width: 1em!important;
  height: 1em!important;
}
.cc-icon svg {
  width: 1em;
  height: 1em;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>